<?php
/**
 * Created by PhpStorm.
 * User: wttfire
 * Date: 2021/2/5
 * Time: 下午2:12
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\exception\ErrorException;
use think\Request;
use think\Validate;

class LvjiApi extends Api {

    //////////////////***********//////////////
    ///
    /// 签名规则：参数列表按key升序后再拼接上&k=lvji456ht，进行MD5加密。
    /// ota.lvji.cn: 接口交互;
    //  maph5.lvji.cn: 导览页面展示;
    //  short.lvji.cn: 驴迹短链服务,将短链接转换为长链;

    //测试服务器域名	https://test-ota.lvji.cn/api
    //生产服务器域名	https://ota.lvji.cn/api/

    protected $key = 'lvji456ht';
    //protected $pro_url = 'https://test-ota.lvji.cn/api/';
    protected $pro_url = 'https://ota.lvji.cn/api/';
    protected $beforeActionList = [
        'verifyLvjiSign'=>[
            'only'=>'pushproductmsg'
        ]
    ];

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function getParamSign($params)
    {
        //签名步骤一：按字典序排序参数
        ksort($params);
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
        $string = $string . "&k=".$this->key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
//        $result = strtoupper($string);
        return $string;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($params)
    {
        $buff = "";
        foreach ($params as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    //获取产品的信息
    public function curlScenicLink($tplId='')
    {
        if(empty($tplId)) return false;
        $reqTime = date('YmdHis');
        $req['tplId'] = rawurlencode(rawurldecode($tplId));
        $req['reqTime'] = $reqTime;
        $url = $this->pro_url.'scenicLink?'.$this->ToUrlParams($req).'&sign='.$this->getParamSign($req);
        trace('驴迹获取产品URL:'.$url);
        $result = Common::http($url);
        $result = json_decode($result,true);
        if(isset($result['status']) && $result['status']==0 && !empty($result['content'])) return $result['content'];
        return [];
    }

    //验签
    public function verifyLvjiSign()
    {
        $request = request();
        $sign = $request->post('sign','');
        if(empty($sign)){
            return $this->result('缺少签名',[],-400,'json');

        }
        $post = $request->post();
        unset($post['sign']);
        $_sign = $this->getParamSign($post);
        if($sign!==$_sign){
            return $this->result('验签失败',[],-400,'json');

        }
    }

    public function getScenicLink($tplId,$rpc = true){
        $result = $this->curlScenicLink($tplId);
        if(empty($rpc)) return $result;
        if(!empty($result)) return $this->result('success',$result,200,'json');
        return $this->result('failed',[],-400,'json');
    }

    //同步产品信息推送（驴迹官方调用）
    public function pushProductMsg(Request $request)
    {
        //验证数据完整性
        $validate = new Validate([
            'tplId'=>'require',
            'price'=>'require',
            'scenicName'=>'require',
            'provinceName'=>'require',
            'cityName'=>'require',
            'type'=>'require',
            'productNotice'=>'require',
            'sign'=>'require',
        ],[
            'tplId.require'=>'缺少模板id',
            'price.require'=>'缺少价格',
            'scenicName.require'=>'缺少景区名称',
            'provinceName.require'=>'缺少所属省',
            'cityName.require'=>'缺少所属市',
            'type.require'=>'缺少推送类型',
            'productNotice.require'=>'缺少产品须知',
            'sign.require'=>'缺少sign参数',
        ]);
        $post = $request->post();
        if(!$validate->check($post)){
            return $this->result($validate->getError(),[],-400,'json');
        }
        //根据类型处理
        $type = $post['type']??'';
        if(!in_array($type,['add','update','delete'])){
            return $this->result("推送类型不支持",[],-400,'json');;
        }
        unset($post['type'],$post['sign']);
        $exist = db('lvji_products')->where(['tplId'=>$post['tplId']])->find();
        db()->startTrans();
        try{
            if($type=='delete'){
                if(!empty($exist)){
                    $postData['is_delete'] = 1;
                    $postData['delete_time'] = time();
                    db('lvji_products')->where(['id'=>$exist['id']])->update($postData);
                }
            }elseif(in_array($type,['add','update'])){
                if(!empty($exist)){
                    $post['update_time'] = time();
                    db('lvji_products')->where(['id'=>$exist['id']])->update($post);
                }else{
                    $post['create_time'] = time();
                    db('lvji_products')->insert($post);
                }
            }

            db()->commit();
            return $this->result('success',[],200,'json');
        }catch (\ErrorException $e){
            db()->rollback();
            trace('同步驴迹商品失败,原因是'.$e->getMessage());
            return $this->result($e->getMessage(),[],-400,'json');
            return $this->result('fail',[],-400,'json');
        }
    }

    //工具 keyValue 转化为 json
    public function KVToJson(Request $request)
    {
        $post = $request->post();
        if(empty($post)) return $this->result('缺少参数',[],-400,'json');

        return json_encode($post);
    }

    //获取测试签名
    public function getTestSign(Request $request)
    {
        $post = $request->post();
        if(empty($post)) return $this->result('缺少参数',[],-400,'json');

        $sign = $this->getParamSign($post);
        return $this->result('success',$sign,200,'json');

    }
}